﻿function el(str) { return document.querySelector(str); }
function els(str) { return document.querySelectorAll(str); }
function ajax(url, params, func,func2) {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function () {//Call a function when the state changes.
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
			func(xmlhttp.responseText);
		}
		if (func2 != undefined && xmlhttp.readyState == 4) {
			func2();
		}
	}
	xmlhttp.open("POST", url, true);
	xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlhttp.send(params);
}
function ajaxSubmit(id) {
	var elsi = els("form#" + id + " input" + '[data-val="true"]');
	var str = "";
	for (var i = 0; i < elsi.length; i++) {
		str += elsi[i].getAttribute("name");
		str += "=";
		if (elsi[i].getAttribute("type") == "checkbox")
			str += elsi[i].checked;
		else
			str += elsi[i].value;
		str += "&";
	}
	str = str.substr(0, str.length - 1);
	ajax(el("form#" + id).getAttribute("Action"), str, function (ret) { el("form#" + id).outerHTML = ret; z.status.saved(); });
}
function ajaxTrSubmit(id) {
	var elsi = els("tr#" + id + " input" + ':not([type="hidden"])');
	var str = "";
	for (var i = 0; i < elsi.length; i++) {
		str += elsi[i].getAttribute("name");
		str += "=";
		if (elsi[i].getAttribute("type") == "checkbox")
			str += elsi[i].checked;
		else
			str += elsi[i].value;
		str += "&";
	}
	str = str.substr(0, str.length - 1);
	ajax(el("tr#" + id).getAttribute("title"), str, function (ret) { el("tr#" + id).outerHTML = ret; z.status.saved(); });
}
function openPopup(str, url) {
	el(str).innerHTML = "";
	ajax(url, "", function (ret) {
		el(str).innerHTML = ret;
	}, function () {
		el(str).className = "popup";
		var eli = document.createElement("div");
		eli.setAttribute("onclick", "closePopup(this.parentElement);");
		eli.className = "close";
		el(str).appendChild(eli);
	});
}
function showPopup(str) {
	el(str).className = "popup";
}
function closePopup(element) {
	element.className = "popupHidden";
	setTimeout(
			function () {
				element.className = "hidden";
			}, 500);
}
z = {};
z.status = {
	saved: function () {
		el("#status").innerHTML = "Saved";
		el("#status").className = "status";
		setTimeout(
			function () {
				el("#status").className = "";
			}, 1000);
	}
}
function zOnEnter(evt,func) {
	var key;

	if (window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //Firefox & others

	if (key == 13) {
		func();
		return false;
	} else {
		return true;
	}
}